import { sample } from "lodash-es";
import Ground from "./Ground";

// 这个场景内的变量
const $ = { speed: 10, state: "running", force: 16, Score: 0 };

// 游戏逻辑的主要函数
export default class Main extends Laya.Script {
    // 这一堆注释是特定写法，用于 LayaAir 进行挂载场景中的物体
    /** @prop { name:Ground, tips:"", type:Node, default:null} */
    /** @prop { name:Ground2, tips:"", type:Node, default:null} */
    /** @prop { name:Tex, tips:"", type:Node, default:null} */
    /** @prop { name:Score, tips:"", type:Node, default:null} */
    /** @prop { name:GameOverLog, tips:"", type:Node, default:null} */
    /** @prop { name:Tree, tips:"", type:Prefab, default:null} */
    /** @prop { name:Tree1, tips:"", type:Prefab, default:null} */
    Ground: Ground;
    Ground2: Ground;
    Tex: Laya.Sprite;
    Tree: Laya.Prefab;
    Tree1: Laya.Prefab;
    Score: Laya.Text;
    GameOverLog: Laya.Sprite;
    constructor() {
        super();
    }
    onAwake(): void {
        console.group("游戏布置完成");

        console.groupEnd();
    }
    // 游戏开始逻辑，同时布置一下 重置的弹窗
    onStart(): void {
        const restartBtn = this.GameOverLog.getChildByName("restart");
        restartBtn.on(Laya.Event.CLICK, this, this.restart);
        this.restart();
    }

    // 游戏每一帧进行的逻辑
    onUpdate(): void {
        if ($.state === "running") {
            $.Score += 1;
            this.Score.text = $.Score + "";
            this.GenA();
            this.SpeedUp();
        }
    }
    // 游戏重启时将数据重新设置为初始状态
    restart() {
        $.speed = 10;
        $.Score = 0;
        $.state = "running";

        this.Ground.changeSpeed();
        this.Ground2.changeSpeed();

        // Tex 上挂载了 reset 让小恐龙归位
        (this.Tex as any).reset();

        // 清空障碍物
        this.resources.tree.forEach((i) => i.destroy());
        this.GameOverLog.visible = false;
    }

    // 设置分数越高，速度越快的逻辑
    SpeedUp() {
        if ($.Score % 300 === 0) {
            $.speed += 1;
            // 这里使用 changeSpeed 进行单个物体的速度调整，保证所有物体的速度是统一加速的
            [this.Ground, this.Ground2, ...this.resources.tree].forEach((i) =>
                (i as any).changeSpeed()
            );
        }
    }
    resources: {
        tree: Laya.Node[];
    } = {
        tree: [],
    };

    // 生成树的方法
    GenA() {
        if ($.Score % 75 === 0 && Math.random() > 0.4) {
            // 选择一种树并添加到舞台上
            const a: Laya.Prefab[] = [this.Tree, this.Tree1];
            const tree = sample(a).create();
            this.resources.tree.push(tree);
            this.owner.addChildren(tree);
        }
    }

    GameOver() {
        $.speed = 0;
        $.state = "over";
        console.log("stop");
        [this.Ground, this.Ground2, ...this.resources.tree].forEach((i) =>
            // 这里使用 changeSpeed 进行单个物体的速度调整，保证所有物体的速度是统一加速的
            (i as any).changeSpeed()
        );
        this.GameOverLog.visible = true;
    }
}
export { $ };
